package xyz.csmcool.imgateway.config;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.stream.Collectors;

/**
 * @author 什锦
 * @Package xyz.csmcool.imgateway.config
 * @since 2022/9/8 10:52
 */
@Configuration
public class ErrorHandlerConfiguration {

    @Bean
    @Order(-1) //设置优先级
    public DefaultErrorWebExceptionHandler defaultErrorWebExceptionHandler(
            ErrorAttributes errorAttributes,
            org.springframework.boot.autoconfigure.web.ResourceProperties resourceProperties,
            ServerProperties serverProperties,
            ObjectProvider<ViewResolver> viewResolvers,
            ServerCodecConfigurer serverCodecConfigurer,
            ApplicationContext applicationContext
    ) {

        JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(
                errorAttributes,
                resourceProperties,
                serverProperties.getError(),
                applicationContext);

        exceptionHandler.setViewResolvers(viewResolvers.orderedStream().collect(Collectors.toList()));
        exceptionHandler.setMessageWriters(serverCodecConfigurer.getWriters());
        exceptionHandler.setMessageReaders(serverCodecConfigurer.getReaders());
        return exceptionHandler;
    }
}
